package com.tarena.csmall.sentinel.demo02.ruleinit;

import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.datasource.FileRefreshableDataSource;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.net.URL;
import java.util.List;

/**
 * 通过spi方式，读取这个DatasourceInit类
 * 从而加载自定义的规则
 */
@Slf4j
public class DatasourceInit implements InitFunc {
    @Override
    public void init() throws Exception {
        System.out.println("初始化");
        // 找到文件路径,读取文件二进制,文件内容,转化成flowRule 注册在sentinel
        ClassLoader classLoader = DatasourceInit.class.getClassLoader();
        URL resource = classLoader.getResource("flowRules.json");
        //需要文件的全路径名称
        String filePath = resource.getFile();
        //sentinel提供了现成的方法,将文件读取,转化成flowRule
        ReadableDataSource<String,List<FlowRule>> rulesDatasource=
                new FileRefreshableDataSource<List<FlowRule>>(filePath, new Converter<String, List<FlowRule>>() {
                    @Override
                    public List<FlowRule> convert(String s) {
                        //file里包含的json字符串
                        return JSON.parseArray(s,FlowRule.class);
                    }
                });
        //将数据源注册到sentinel
        FlowRuleManager.register2Property(rulesDatasource.getProperty());
    }
}
